package com.miles.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.log4j.Logger;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class MybatisUntil {
    private static SqlSessionFactory sqlSessionFactory;
    private  Logger logger =Logger.getLogger(this.getClass());

    static {
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = null;
            inputStream = Resources.getResourceAsStream(resource);
             sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public  static SqlSession getSqlSession(){
       return sqlSessionFactory.openSession();
    }


    @Test
    public void  selectAll(){
        UserMapper userDao = getSqlSession().getMapper(UserMapper.class);
        List<User> users = userDao.selectUsers();
        for (User user: users) {
            System.out.println(user.getName());
        }
    }
    @Test
    public void  selectById(){
        UserMapper userDao = getSqlSession().getMapper(UserMapper.class);
        User user = userDao.selectUserById(1);
        System.out.println(user.getName());
    }
    @Test
    public  void  selectCndition(){
        UserMapper userDao = getSqlSession().getMapper(UserMapper.class);
        Map map = new HashMap();
        map.put("id",2);
        map.put("name","guo");
        User user = userDao.selectCndition(map);
        System.out.println(user.getName());
    }

    @Test
    public  void  selectLimit(){
        UserMapper userMapper = getSqlSession().getMapper(UserMapper.class);
        Map map = new HashMap();
        map.put("index",0);
        map.put("pageSize",2);
        List<User> users = userMapper.selectLimit(map);
        for (User user: users) {
            System.out.println(user.getId()+"=="+user.getName()+"=="+user.getPassword());
        }
    }

    public static void main(String[] args) {
        MybatisUntil  m= new MybatisUntil();

       m. selectLimit();
        System.out.println("==========================");
       m. selectLimit();
    }



}
